package com.example.base.tools

import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

class CountdownUtils {
    var count: Int = 60
    var countdownCallBack: CountdownCallBack? = null

    constructor(count: Int, countdownCallBack: CountdownCallBack) {
        this.count = count
        this.countdownCallBack = countdownCallBack


    }

    lateinit var subscribe: Disposable//保存订阅者
    fun start(timeUnit:TimeUnit) {
        Observable.interval(1, timeUnit)//按时间间隔发送整数的Observable
            .observeOn(AndroidSchedulers.mainThread())//切换到主线程修改UI
            .subscribe(object : Observer<Long> {
                override fun onSubscribe(d: Disposable) {
                    subscribe = d
                }

                override fun onNext(t: Long) {
                    val show = count - t
                    if (show <= 0.toLong()) {//当倒计时小于0,计时结束
                        stop(show)
                        return//使用标记跳出方法
                    } else {
                        countdownCallBack?.onCountDown(show)
                    }

                }

                override fun onError(e: Throwable) {
                    stopNoCallBack()
                }

                override fun onComplete() {
                    stopNoCallBack()
                }

            })

    }

    /**
     * 结束计时,重新开始
     */
    fun stopNoCallBack() {

        if (subscribe != null && !subscribe.isDisposed()) {//取消订阅
            subscribe.dispose();
        }
        return
    }

    /**
     * 结束计时,重新开始
     */
    fun stop(show: Long) {
        if (subscribe != null && !subscribe.isDisposed()) {//取消订阅
            subscribe.dispose();
        }
        countdownCallBack ?. onStop (show)

        return
    }


}

interface CountdownCallBack {
    fun onStop(currentTime: Long)
    fun onCountDown(currentTime: Long)
}